import axios from "axios";
import { getToken, setToken } from "./auth";
import { ElMessage, ElMessageBox } from "element-plus";
import errorCode from "./errorCode";
export let isRelogin = { show: false };

// 创建axios实例
const request = axios.create({
  baseURL: "/dev-api", // 设置默认的 API 地址，url = baseURL + url（使用proxy代理时此处可不写）
  timeout: 50000, // 设置请求超时时间       // 设置请求header，可以自定义属性
});

// 请求拦截器
request.interceptors.request.use(
  // 请求配置（全局），一般在登录时后端返回token，此处设置token后，前端每次调取接口都会携带token
  async (config) => {
    const token = getToken();
    if (token) {
      if (config.url != "hik-event/testToken") {
        config.headers.token = token;
        config.headers.Authorization = token;
      }
    } else {
      const loginResponse = await axios.post("/dev-api/login", {
        username: "admin",
        password: "admin123",
      });
      const token = loginResponse.data.data.token;
      setToken(token);
      config.headers.Authorization = token;
      config.headers.token = token;
    }
    return config;
  },
  // 请求错误
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = res.data.msg || errorCode["default"];
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm(
          "登录状态已过期，您可以继续留在该页面，或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            isRelogin.show = false;
            // TODO用户logout，清除token
            axios
              .post("/dev-api/login", {
                username: "admin",
                password: "admin123",
              })
              .then((loginResponse) => {
                const token = loginResponse.data.data.token;
                setToken(token);
              });
          })
          .catch(() => {
            isRelogin.show = false;
          });
      }
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({ message: msg, type: "error" });
      return Promise.reject(new Error(msg));
    } else if (code === 601) {
      ElMessage({ message: msg, type: "warning" });
      return Promise.reject("error");
    } else if (code !== 200) {
      ElMessage({ message: msg, type: "error" });
      return Promise.reject("error");
    } else {
      return res.data;
    }
  },
  (error) => {
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message: message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

export default request;
